package net.oschina.app.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import net.oschina.app.MApp;
import net.oschina.app.R;
import net.oschina.app.adapter.DialogFaceAdapter;
import net.oschina.app.interf.OnRecycleViewItemClickListener;
import net.oschina.app.ui.widget.FaceFactoty;

import static net.oschina.app.emoji.InputHelper.getEmojiResId;

/**
 * Created by foty on 2017/4/7.
 * ?
 */

public class DilogText extends AppCompatActivity {


    private ImageView mIvxc;
    private ImageView mIvjing;
    private ImageView mIvat;
    private ImageView mIvbq;
    private ImageView mSend;
    private RecyclerView mRcv;
    private EditText mEditText;
    private static boolean isVisibal = false;
    private DialogFaceAdapter mFaceAdapter;
    private FaceFactoty mfFactoty = new FaceFactoty();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_text);
        initeView();
        initeEvent();
    }

    private void initeEvent() {
        final String[] single_list = {"相册", "相机"};
        //相册
        mIvxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(DilogText.this);
                builder.setTitle("单选对话框");
                builder.setSingleChoiceItems(single_list, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            //调用相册
                            Intent intentalbum = new Intent(Intent.ACTION_PICK,
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intentalbum, 0);
                        } else {
                            // 启动相机
                            Intent intentphoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intentphoto, 1);

                        }
                        dialog.dismiss();
                    }
                }).create().show();
            }
        });

        //@
        mIvat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MApp.mContext, "哎呀，你还没登陆呢，快去登陆吧", Toast.LENGTH_SHORT).show();
            }
        });

        //#号
        mIvjing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditText.setText("#输入软件名#");
            }
        });

        //表情
        mIvbq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVisibal) {
                    mRcv.setVisibility(View.GONE);
                    isVisibal = false;
                } else {
                    mRcv.setVisibility(View.VISIBLE);
                    isVisibal = true;
                }
            }
        });
    }

    private void initeView() {
        mIvxc = (ImageView) findViewById(R.id.dialog_text_xiangc);
        mIvjing = (ImageView) findViewById(R.id.dialog_text_jing);
        mIvat = (ImageView) findViewById(R.id.dialog_text_at);
        mIvbq = (ImageView) findViewById(R.id.dialog_text_biaoq);
        mSend = (ImageView) findViewById(R.id.dialog_text_send);
        mRcv = (RecyclerView) findViewById(R.id.dialog_text_face);
        mEditText = (EditText) findViewById(R.id.editText);

        GridLayoutManager gManager = new GridLayoutManager(this, 7);
        mRcv.setLayoutManager(gManager);
        mFaceAdapter = new DialogFaceAdapter(this);
        mRcv.setAdapter(mFaceAdapter);
        initeFaceEvent();
    }

    public void initeFaceEvent(){

        mFaceAdapter.setOnItemClickListener(new OnRecycleViewItemClickListener() {
            String text = "";
            @Override
            public void onClick(View view, int position) {
                 Toast.makeText(MApp.mContext, position+"", Toast.LENGTH_SHORT).show();
                String mapKey = mfFactoty.getMapKey(position);
                text = mEditText.getText().toString()+mapKey;

                SpannableString spannableString = new SpannableString(text);
              //  Spannable spannable  = new SpannableString(text);

                /*for (int i = 0;i<text.length();i++){
                    int start = text.indexOf("[", i);
                    int end = text.indexOf("]", start + 1);

                  //  String emojposition = text.substring(start, end + "]".length());
                   *//* // 构建图片span
                    Drawable drawable = getResources().getDrawable(mfFactoty.getFaceID(mapKey));
                   // spannable.setSpan(drawable,start,end + 1,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);*//*

                    Drawable drawable = getResources().getDrawable(mfFactoty.getFaceID(mapKey));
                    ImageSpan imageSpan = new ImageSpan(drawable);
                    spannableString.setSpan(imageSpan, start, end,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                }*/
                mEditText.setText(spannableString);

               // mEditText.setText(spannable);
            }
        });

    }

    //清空文本内容的方法
    public void clear(View v) {
        AlertDialog.Builder normalDia = new AlertDialog.Builder(DilogText.this);
        normalDia.setIcon(R.drawable.ic_launcher)
                .setTitle("清空")
                .setMessage("确认清除所有内容么?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mEditText.setText("");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();

    }


    public static Spannable displayEmoji(Resources res, CharSequence s) {
        String str = s.toString();
        Spannable spannable = null;
        if (s instanceof Spannable) {
            spannable = (Spannable) s;
        } else {
            // 构建文字span
            spannable = new SpannableString(str);
        }
        for (int i = 0; i < str.length(); i++) {
            int index1 = str.indexOf("[", i);
            int length1 = str.indexOf("]", index1 + 1);
            int index2 = str.indexOf(":", i);
            int length2 = str.indexOf(":", index2 + 1);
            int bound = (int) res.getDimension(R.dimen.space_20);
            try {
                String emojiStr = str.substring(index1, length1 + "]".length());
                int resId = getEmojiResId(emojiStr);
                if (resId > 0) {
                    // 构建图片span
                    Drawable drawable = res.getDrawable(resId);

                    drawable.setBounds(0, 20, bound, bound + 20);
                    ImageSpan span = new ImageSpan(drawable,
                            ImageSpan.ALIGN_BASELINE);
                    spannable.setSpan(span, index1, length1 + "]".length(),
                            Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                }
            } catch (Exception e) {
            }
            try {
                String emojiStr2 = str
                        .substring(index2, length2 + ":".length());
                int resId2 = getEmojiResId(emojiStr2);
                if (resId2 > 0) {
                    Drawable emojiDrawable = res.getDrawable(resId2);
                    emojiDrawable.setBounds(0, 0, bound, bound);
                    // 构建图片span
                    ImageSpan imageSpan = new ImageSpan(emojiDrawable, str);
                    spannable.setSpan(imageSpan, index2,
                            length2 + ":".length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } catch (Exception e) {
            }
        }
        return spannable;
    }
}
